package Q859;

import java.util.Arrays;

/**
 * 每日一题之亲密字符串
 * 给你两个字符串 s 和 goal ，只要我们可以通过交换 s 中的两个字母得到与 goal 相等的结果，就返回 true ；
 * 否则返回 false 。
 * @author 23737
 * @time 2021.11.23
 */
public class Test {
    public static void main(String[] args) {
        System.out.println(new Solution().buddyStrings("aa", "aa"));
        System.out.println(new Solution().buddyStrings("ab", "aa"));
        System.out.println(new Solution().buddyStrings("ab", "ba"));
        System.out.println(new Solution().buddyStrings("de", "de"));
    }
}

/**
 * 字符计数
 */
class Solution {
    public boolean buddyStrings(String s, String goal) {
        if (s.equals(goal)) {
            if (s.length() == 1) {
                return false;
            }
            int[] chars = new int[26];
            for (char c : goal.toCharArray()) {
                int num = ++chars[c - 'a'];
                if (num == 2) {
                    return true;
                }
            }
            return false;
        } else if (s.length() == goal.length()) {
            char[] ss = s.toCharArray();
            char[] gs = goal.toCharArray();
            int mark = 0;
            char d1 = ' ';
            char d2 = ' ';
            for (int i = 0; i < s.length(); i++) {
                char c1 = ss[i];
                char g1 = gs[i];
                if (c1 != g1) {
                    if (mark == 0) {
                        d1 = c1;
                        d2 = g1;
                        mark++;
                        continue;
                    } else if (mark == 1) {
                        if (d1 != g1 || d2 != c1) {
                            return false;
                        }
                        mark++;
                        continue;
                    }
                    return false;
                }
            }
            return mark == 2;
        }
        return false;
    }
}

